package com.qf.web.sys_role.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.web.sys_menu.entity.Menu;
import com.qf.web.sys_menu.entity.MenuTree;
import com.qf.web.sys_menu.servie.MenuService;
import com.qf.web.sys_role.entity.Role;
import com.qf.web.sys_role.entity.RolePrams;
import com.qf.web.sys_role.mapper.RoleMapper;
import com.qf.web.sys_role.service.RoleService;
import com.qf.web.sys_user.entity.AssignParams;
import com.qf.web.sys_user.entity.AssignVo;
import com.qf.web.sys_user.entity.User;
import com.qf.web.sys_user.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * @author xufuhan
 * @Date 2024/9/10 16:40
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;
    @Override
    public IPage<Role> list(RolePrams prams) {
        //构造分页对象
        IPage<Role> page = new Page<>();
        page.setCurrent(prams.getCurrentPage());
        page.setPages(prams.getPageSize());
        //构造查询条件
        QueryWrapper<Role> query = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(prams.getRoleName())){
            query.lambda().like(Role::getRoleName,prams.getRoleName());
        }
        return this.baseMapper.selectPage(page,query);
    }

    @Override
    public AssignVo getAssignShow(AssignParams params) {
        //查询当前用户信息
        User user = userService.getById(params.getUserId());
        List<Menu> list=null;
        //判断身份
        if (user.getIsAdmin() == 1){
            //超管直接查询所有权限
            QueryWrapper<Menu> wrapper=new QueryWrapper<>();
            wrapper.lambda().orderByAsc(Menu::getOrderNum);
            list=menuService.list(wrapper);
        }else {
            //不是就查询自己权限
            list=menuService.getMenuByUserId(params.getUserId());
        }
        //组装菜单树
        List<Menu> menus = MenuTree.makeManuTree(list,0L);
        //查询角色原本权限
        List<Menu> menuByRoleId = menuService.getMenuByRoleId(params.getRoleId());
        //过滤出id
        List<Long> ids=new ArrayList<>();
        Optional.ofNullable(menuByRoleId).orElse(new ArrayList<>())
                .stream()
                .filter(item->item!=null)
                .forEach(item->{
                    ids.add(item.getMenuId());
                });
        //组装返回
        AssignVo vo=new AssignVo();
        vo.setCheckList(ids.toArray());
        vo.setMenuList(menus);
        return vo;
    }
}
